﻿namespace BEGDC.CC.Web.EZVisit.Controls
{
    #region Using Directives

    using System;
    using System.Data;
    using System.Linq;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using ASBCC.Database.Entity;
    using ASBCC.Database.Service;
    using Utility.Extensions;

    #endregion

    public partial class EZVRequestAftAttachment : EZVRequestBaseControl
    {
        protected override void PreRenderPartialView()
        {
            this.SetVisibility();
            this.SetViewData();
        }

        protected override void SetViewData()
        {
            if (this.EZVisitApplication == null)
            {
                return;
            }

            this.lblTitle.Text = string.Format("Host post-trip confirmation({0})接待方事后确认（{1}）：", this.EZVisitApplication.IsDomestic.Value ? "domestic" : "oversea", this.EZVisitApplication.IsDomestic.Value ? "国内" : "海外");
            this.lbAppNo.Text = this.EZVisitApplication.AppNo;

            if (this.Editable)
            {
                this.edt_AgendaChanged.SelectedValue = this.EZVisitApplication.IsAgendaChanged == null || !this.EZVisitApplication.IsAgendaChanged.Value ? "0" : "1";
                this.edt_CustomerChanged.SelectedValue = this.EZVisitApplication.IsCustomerChanged == null || !this.EZVisitApplication.IsCustomerChanged.Value ? "0" : "1";
            }
            else
            {
                this.vw_AgendaChanged.Text = this.EZVisitApplication.IsAgendaChanged == null || !this.EZVisitApplication.IsAgendaChanged.Value ? "No" : "Yes";
                this.vw_CustomerChanged.Text = this.EZVisitApplication.IsCustomerChanged == null || !this.EZVisitApplication.IsCustomerChanged.Value ? "No" : "Yes";
            }

            this.BindAttachments(false);
        }

        protected override void SetVisibility()
        {
            base.SetVisibility();

            this.dgAttachment.Columns[7].Visible = this.Editable;
        }

        protected override bool Validate(out string error)
        {
            error = string.Empty;

            if (this.CurrentActionType.IsNotNullOrWhiteSpace())
            {
                if (this.edt_Upload1.Visible)
                {
                    error = @"- [Post Trip] Host post-trip confirmation attachment was not provided. \n";
                }

                if (this.edt_Upload3.Visible)
                {
                    error += @"- [Post Trip] TA settlement attachment was not provided. \n";
                }

                if (this.edt_AgendaChanged.SelectedValue.Equals("1") && this.edt_Upload5.Visible)
                {
                    error += @"- [Post Trip] Agenda attachment was not provided. \n";
                }

                if (this.edt_CustomerChanged.SelectedValue.Equals("1") && this.edt_Upload6.Visible)
                {
                    error += @"- [Post Trip] Customers list attachment was not provided. \n";
                }
            }

            return error.Length == 0;
        }

        public override void Save(EZVisitApplicationTableEntity app)
        {
            if (app == null)
            {
                return;
            }

            app.IsAgendaChanged = this.edt_AgendaChanged.SelectedValue.Equals("1");
            app.IsCustomerChanged = this.edt_CustomerChanged.SelectedValue.Equals("1");

            base.Save(app);
        }

        public void BindAttachments(bool reloadView)
        {
            if (this.EZVisitApplication == null || this.EZVisitApplication.AppID == null || !this.Visible)
            {
                return;
            }

            string hostConfirmation = this.EZVisitApplication.IsDomestic.Value ? "'HostPostTripConfirmationDomestic'" : "'HostPostTripConfirmationOversea'";

            var range = new[] { hostConfirmation, "'AgendaChanged'", "'TASettlement'", "'EZVisitReapprovalMail'", "'CustomerChanged'" };
            var dt = this.GetAttachments(range).OfType<UploadFileTableEntity>().ToDataTable();

            this.dgAttachment.DataSource = dt;
            this.dgAttachment.DataBind();

            bool agendaChanged = this.edt_AgendaChanged.SelectedValue.Equals("1");
            bool customerChanged = this.edt_CustomerChanged.SelectedValue.Equals("1");

            this.lblStar.Visible = agendaChanged;
            this.lblStar1.Visible = customerChanged;

            if (!this.Editable)
            {
                return;
            }

            if (reloadView && (agendaChanged || customerChanged))
            {
                this.Save(this.EZVisitApplication);
            }

            this.edt_Upload1.OnClientClick = "return openUploadPanel(" + hostConfirmation + ")";
            this.edt_Upload1.Visible = true;
            this.edt_Upload3.Visible = true;
            this.edt_Upload4.Visible = true;
            this.edt_Upload5.Visible = true;
            this.edt_Upload6.Visible = true;

            foreach (DataRow row in dt.Rows)
            {
                switch (row["AttachmentTypeKey"].ToString().ToLowerInvariant())
                {
                    case "hostposttripconfirmationdomestic":
                    case "hostposttripconfirmationoversea":
                        this.edt_Upload1.Visible = false;
                        break;
                    case "agendachanged":
                        this.edt_Upload5.Visible = false;
                        break;
                    case "customerchanged":
                        this.edt_Upload6.Visible = false;
                        break;
                    case "tasettlement":
                        this.edt_Upload3.Visible = false;
                        break;
                    case "ezvisitreapprovalmail":
                        this.edt_Upload4.Visible = false;
                        break;
                }
            }
        }

        protected void dgAttachment_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if ((e.Item.ItemType != ListItemType.Item) && (e.Item.ItemType != ListItemType.AlternatingItem))
            {
                return;
            }

            var cell = e.Item.Cells[7];

            var btnDelete = (ImageButton)cell.FindControl("btnDelete");
            btnDelete.Attributes.Add("onclick", "return confirm('Are you sure to delete this item?');");
        }

        protected void dgAttachment_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            DeleteAttachement(Convert.ToInt32(e.Item.Cells[0].Text));

            string attchType = e.Item.Cells[6].Text;

            if (attchType.IsNotNullOrWhiteSpace())
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "reload" + attchType, "reload('" + attchType + "');", true);
            }
        }

        private UploadFileTableEntitySet GetAttachments(string[] attchTypes)
        {
            string rangeCondition = string.Join(",", attchTypes);

            string condition = string.Format("AppID={0} and AppType='EZV' and IsEnabled=1 and AttachmentTypeKey in ({1})", this.EZVisitApplication.AppID, rangeCondition);

            return UploadFileManager.SelectByCondition(condition);
        }

        private static void DeleteAttachement(int fileId)
        {
            var attachment = UploadFileManager.SelectByKeys(fileId);

            if (attachment == null)
            {
                return;
            }

            attachment.IsEnabled = false;
            UploadFileManager.Update(attachment);
        }

        protected void edt_AgendaChanged_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.lblStar.Visible = this.edt_AgendaChanged.SelectedValue.Equals("1");
        }

        protected void edt_CustomerChanged_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.lblStar1.Visible = this.edt_CustomerChanged.SelectedValue.Equals("1");
        }
    }
}